import React from 'react';
import {SubmitHandler, useForm} from 'react-hook-form';
import Button from "@/components/ui/Button/Button";
import styles from "./RegistrationForm.module.css";
import FormInput from "@/components/ui/Forms/FormElements/FormInput";
import {TypeLoginFormProps, TypeUser} from "@/shared/types";
import {postObjWithoutToken} from "@/services/api_service";
import {handleLogin} from "@/lib/actions";
import {useRouter} from "next/navigation";

export const emailPattern = {
    value: new RegExp('^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$', 'ig'),
    message: 'Неверный формат электронной почты.',
};

export default function RegistrationForm({setModalOpen, setCurrentAuthForm}: TypeLoginFormProps) {
    const {
        register,
        handleSubmit,
        formState: {errors},
        getValues,
    } = useForm<TypeUser>();
    const {replace} = useRouter()

    const onSubmit: SubmitHandler<TypeUser> = async (data) => {

        const response = await postObjWithoutToken('/api/auth/register/', JSON.stringify(data));
        if (response.access) {
            await handleLogin(response.id, response.access, response.refresh);

            setModalOpen(false)
            setCurrentAuthForm("none")

            replace('/user')
        } else {
            console.log('Ошибка регистрации')
        }
    }

    return (
        <form onSubmit={handleSubmit(onSubmit)}
              className={styles.loginForm_container}>

            <FormInput<TypeUser>
                id="email"
                type="email"
                name="email"
                kind="email"
                label="Электронная почта"
                placeholder="ivanov@mail.com"
                register={register}
                rules={{
                    required: "Введите электронную почту",
                    pattern: emailPattern
                }}
                errors={errors}
            />

            <FormInput<TypeUser>
                id="password"
                type="password"
                name="password"
                kind="password"
                label="Пароль"
                placeholder="Пароль"
                register={register}
                rules={{
                    required: "Введите пароль",
                    minLength:
                        {
                            value: 8,
                            message: "Длина пароля должна быть не менее 8 символов"
                        },
                    maxLength: {
                        value: 24,
                        message: "Длина пароля должна быть не более 24 символов"
                    }
                }}
                errors={errors}
            />

            <FormInput<TypeUser>
                id="secondPassword"
                type="password"
                name="password2"
                kind="password"
                label="Повторите пароль"
                placeholder="Повторите пароль"
                register={register}
                rules={{
                    required: "Подтвердите пароль",
                    validate: {
                        matchesPreviousPassword: (value) =>
                            value === getValues("password") || "Пароли не совпадают"
                    }
                }}
                errors={errors}
            />

            <div className={styles.buttons_container}>
                <Button type="submit" kind="submit" content="Зарегистрироваться"/>
                <Button type="button" kind="secondary" content="К входу"
                        onClick={() => {
                            setModalOpen(false)
                            setCurrentAuthForm("login")
                        }}/>
            </div>
        </form>
    );
}